#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2020-12-29 10:56
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：

import os
import subprocess
import sys
import time_ext_


class Build(object):
    """docstring for Build"""

    def __init__(self, file_name, icon = None, out_dir = None, gui = None, plugin = None ):
        super(Build, self).__init__()
        self.file_name = file_name
        self.exe_name = os.path.splitext(os.path.split(self.file_name)[-1])[0]
        self.icon = icon
        self.gui = gui
        self.plugin = plugin
        self.out_dir = self.create_dir(out_dir)

    # 创建打包输出目录
    def create_dir(self, out_dir):
        out_dir = os.path.abspath(out_dir) if out_dir else None
        if out_dir and os.path.exists(out_dir):
            return out_dir if os.path.isabs(out_dir) else os.path.abspath(out_dir)
        if (out_dir and not os.path.exists(out_dir)) or not out_dir:
            file_dir = os.path.dirname(self.file_name)
            out_dir = os.path.join(file_dir, '{}.dist'.format(self.exe_name))
            os.mkdir(out_dir) if not os.path.exists(out_dir) else None
            return out_dir

    # 创建打包命令
    def build_command(self):
        command = r"E:\app\.virtualenvs\3.7\Scripts\nuitka "
        # command += " --recurse-all "
        command += "--standalone"
        command += " --windows-disable-console " if self.gui else ""
        command += " --windows-icon-from-ico={} ".format(os.path.abspath(self.icon)) if self.icon else ""
        command += "  --show-memory --show-progress "
        command += "  --plugin-enable=%s " % self.plugin  if self.plugin else ""
        command+=self.get_rc()
        command += " --output-dir=D:/YGSOFT/ICS/Interface/ "
        command += self.file_name
        print("打包命令:{}".format(command))
        return command
    def get_rc(self):
        file_dir =os.path.dirname(self.file_name)
        rc_list =[]
        for file in os.listdir(file_dir):
            file_path =os.path.join(file_dir,file)
            if os.path.isfile(file_path) and '_rc.py' in file:
                rc_list.append("--include-module={} ".format(os.path.splitext(file)[0]))
        return  "".join(rc_list)
    # 结束打包后exe
    def kill_exe(self):
        time_ext_.sleep(1)
        app_name = "{}.exe".format(self.exe_name)
        exec_comand = "TASKKILL /F /IM {}".format(app_name).encode("gbk")
        try:
            subprocess.Popen(exec_comand, shell = False)
        except Exception as e:
            print("结束程序:{},失败:{}".format(app_name, e))

    # 扫描模块
    def search_module(self, module_name):
        print("扫描缺失的模块:{}".format(module_name))
        env_dir = [path for path in sys.path if '\lib\site-packages' in path][0]
        # 自定义模块路径
        module_dir = r"E:\app\common"
        path_list = [env_dir, module_dir, os.path.dirname(self.file_name)]
        for path in path_list:
            for root, dirs, files in os.walk(path):  # path 为根目录
                if module_name in dirs or module_name in files:
                    return os.path.join(root, module_name)
                module_pyd =self.search_pyd(module_name,files)
                if module_pyd:
                    return os.path.join(root,module_pyd)

    def search_pyd(self,module_name,files):
        for file_name in files:
            if file_name.split('.')[0]==module_name :
                return file_name

    # 运行
    def run(self):
        command = self.build_command()
        with open(os.path.join(os.path.dirname(self.file_name),'command.bat'),'w') as f:
            f.write(command)
        os.system(command)


if __name__ == '__main__':
    # args = [r'D:\CODE\PYTHON\DA_V3\app.py', 'D:\CODE\PYTHON\DA_V3\icon.ico','./']
    app= Build(*sys.argv[1:])
    # app = Build(*args)
    app.run()